<template>
	<div style="width:100%;">
		<el-row>
			<el-col :span="23">
				<el-form-item
					:prop="courseNoStr"
					:label="title">
					<el-cascader
						v-model="course.courseNoStr"
						@change="selectChange"
						clearable
						@clear="clearSelect"
						:options="courseList"
						:disabled="showBtn?false:true"
					/>
				</el-form-item>
			</el-col>
			<el-col v-if="!showBtn" style="text-align: center;" :span="1">
				<slot></slot>
			</el-col>
			<el-col v-else style="text-align: center;" :span="1">
				<slot></slot>
			</el-col>
		</el-row>
	</div>
</template>

<script lang="ts" setup>
import { defineProps, defineEmits, ref, PropType, onMounted } from 'vue';
import { searchCourse } from '/@/api/course';

let courseList = ref([] as any);
const props = defineProps({
	course: {
		type: Object,
		default: {}
	},
	title: {
		type: String,
		default: '选择课程'
	},
	showBtn: {
		type: Boolean,
		default: true
	}
});
const emit = defineEmits(['change','clear']);

// 处理级联选择器变化
const selectChange = () => {
	if (props.course.courseNoStr) {
		let selected = props.course.courseNoStr[props.course.courseNoStr.length - 1]
		emit('change', selected);
	} else {
		emit('clear');
	}
};
const clearSelect = () => {
	emit('clear');
}
onMounted(async () => {
	try {
		const res = await searchCourse({});
		courseList.value = convertToCascaderFormat(res.data.list);
	} catch (error) {
		console.error('获取课程列表失败:', error);
	}
});

/**
 * 将原始课程数据转换为级联选择器所需格式
 * @param originalList 原始课程列表数据
 * @returns 级联选择器格式数据 [{ value: ..., label: ..., children: [...] }]
 */
const convertToCascaderFormat = (originalList: any[]) => {
	return originalList.map(course => ({
		value: course.courseNo.toString(),
		label: course.name,
		children: convertChaptersToChildren(course.chapterTrees, course.courseNo.toString())
	}));
};

/**
 * 递归处理章节/小节数据
 * @param chapters 章节/小节数组
 * @param parentCode 父级编码
 * @returns 转换后的子级数组
 */
const convertChaptersToChildren = (chapters: any[], parentCode: string) => {
	if (!chapters || chapters.length === 0) return [];

	return chapters.map(chapter => {
		const fullCode = `${parentCode},${chapter.chapterNo}`;
		return {
			value: fullCode,
			label: chapter.name,
			children: convertChaptersToChildren(chapter.children, fullCode)
		}
	});
};
</script>

<style scoped lang="scss">
.a-select {
	padding-left: 120px;
	margin-bottom: 16px;

	.item {
		float: left;
		width: 270px;
		margin-right: 12px;
	}
}
</style>
